# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt, ini_opt_school
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')

        # 下载考勤模板
        url = main_repo_data.get('考勤模板.xlsx')
        if url:
            if gitee_opt.download_file('金牛区相关信息/考勤模板.xlsx', 'file/考勤模板.xlsx'):
                log_opt.write_success(f'成功获取gitee数据，【考勤模板.xlsx】下载成功！')
                # 获取ini数据
                url = main_repo_data.get("重要配置.ini")
                if url:
                    da = gitee_opt.get_gitee_repo_file(url)
                    if da:
                        ini_opt.read_ini_string(da)
                        log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                        url_2 = main_repo_data.get("学校配置.ini")
                        if url_2:
                            da = gitee_opt.get_gitee_repo_file(url_2)
                            if da:
                                ini_opt_school.read_ini_string(da)
                                log_opt.write_success(f'成功获取gitee数据，【学校配置.ini】信息成功！')
                                return True
                            else:
                                raise Exception('获取【学校配置.ini】信息失败！')
                        else:
                            raise Exception('未找到-【学校配置.ini】！')
                    else:
                        raise Exception('获取【重要配置.ini】信息失败！')
                else:
                    raise Exception('未找到-【重要配置.ini】！')
            else:
                raise Exception('【考勤模板.xlsx】下载失败！')
        else:
            raise Exception('未找到-【考勤模板.xlsx】！')

    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 数据清洗
def clean_data(file_path):
    """
    清洗数据
    :param ex:excel对象
    :return:
    """
    ex = excel_package.Excel_Option(file_path)
    ex.open_file()
    try:
        for sheet in ex.list_sheets():
            '''删除所有格式'''
            ex.clear_region_format(sheet)

            '''文本居中'''
            ex.modify_region_alignment(sheet, horizontal="center", vertical="center")

            '''删除None列'''
            while True:
                k = ex.get_sheet_headers(sheet)
                # print(k)
                if None in k:

                    # print(sheet)
                    ex.delete_column(sheet, k.index(None) + 1)
                else:
                    break

            '''删除None行'''
            # 配置行
            k = ex.get_column_values(sheet, "A")
            # 如果第一列数据是有行是None就要删除这一行
            while True:
                k = ex.get_column_values(sheet, "A")
                if None in k:
                    # print(k)
                    ex.delete_row(sheet, k.index(None) + 1)
                    # print(sheet)
                else:
                    break

            '''重置索引'''
            rows = ex.get_sheet_max_rows(sheet)
            p = 1
            for i in range(2, rows + 1):
                ex.modify_cell_value(sheet, i, 1, p)
                p += 1
        ex.save_file()
        ex.close_file()
        return True
    except Exception as e:
        ex.close_file()
        return False


# 分割学校名称
def extract_school_name(item):
    if "竞赛" in item:
        match = re.search(r'(\w+)竞赛', item)
        if match:
            return match.group(1)
        else:
            return None

    elif "普" in item:
        match = re.search(r'(\w+)普', item)
        if match:
            return match.group(1)
        else:
            return None
    else:
        return None


# 分割年级
def extract_text_by_nodes(text):
    patterns = [r'(.*?)(普|竞赛)(.*)', r'(.*)(普|竞赛)$']
    for pattern in patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1), match.group(2), match.group(3)
    return "", "", ""


# 生成考勤表
def creat_kao_qin_sheet(file_path):
    ex_main = excel_package.Excel_Option(file_path)
    ex_main.open_file()
    sheet_names = ex_main.list_sheets()
    try:
        if "竞赛模板" in sheet_names:
            sheet_names.remove("竞赛模板")
        if "普模板" in sheet_names:
            sheet_names.remove("普模板")
        # 生产项目学校字典
        school_names = dict()
        for i in ini_opt_school.config.sections():
            school_names[i] = []
        js_sheet_names = []
        pj_sheet_names = []

        # 分类班级
        for sheet in sheet_names:
            if "竞赛" in sheet:
                js_sheet_names.append(sheet)
            else:
                pj_sheet_names.append(sheet)

        # 把班级分至学校
        for school in school_names.keys():
            for op in ini_opt_school.list_section_options(school):
                for pj_sheet in pj_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(pj_sheet):
                        school_names[school].append(pj_sheet)
                for js_sheet in js_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(js_sheet):
                        school_names[school].append(js_sheet)

        os_opt.make_file_folder('file/考勤表')
        # 生成考勤表
        for school, sheets in school_names.items():
            # 创建文件夹
            os_opt.make_file_folder(f"file/考勤表/{school}")

            for sheet in sheets:
                ex_mb = excel_package.Excel_Option("file/考勤模板.xlsx")
                ex_mb.open_file()

                sheet_kq = ex_mb.list_sheets()
                sheet_kq = sheet_kq[0]

                '''提取基本数据'''
                # 修改学校
                ex_mb.modify_cell_value(sheet_kq, 1, 2, school)
                # 修改年级
                nj = extract_text_by_nodes(sheet)[2]
                # 年份
                nf = time_opt.current_year()

                # 班型
                if extract_text_by_nodes(sheet)[1] != "竞赛":
                    bx = "普教"
                else:
                    bx = extract_text_by_nodes(sheet)[1]
                # 季节
                if time_opt.current_month() > 6:
                    jj = "秋季"
                else:
                    jj = "春季"
                # print(jj)

                bt = f"{nf}年{jj}{school}{nj}年级{bx}考勤表"
                # print(bt)
                mb_headers = ex_mb.get_sheet_headers(sheet_kq, 4)
                while None in mb_headers:
                    mb_headers.remove(None)

                # 准备数据
                mb_data = {}
                all_data = ex_main.get_sheet_all_data(sheet)
                for v, d in all_data.items():
                    for _ in mb_headers:
                        mb_data[_] = d[_]
                    # 插入数据

                    rows = ex_mb.get_sheet_max_rows(sheet_kq)
                    ex_mb.insert_row(sheet_kq, rows + 1)
                    for k in mb_headers:
                        ex_mb.modify_cell_value(sheet_kq, rows + 1, mb_headers.index(k) + 1, mb_data[k])

                # 修改标题
                ex_mb.modify_cell_value(sheet_kq, 2, 1, bt)
                ex_mb.modify_cell_value(sheet_kq, 1, 2, school)
                ex_mb.modify_cell_value(sheet_kq, 1, 4, nj)
                ex_mb.modify_cell_value(sheet_kq, 1, 6, nf)
                ex_mb.modify_cell_value(sheet_kq, 1, 8, bx)
                ex_mb.modify_cell_value(sheet_kq, 1, 10, jj)

                # 修改格式
                for k in range(5, ex_mb.get_sheet_max_rows(sheet_kq) + 1):
                    ex_mb.modify_specific_row_height(sheet_kq, k, 30)
                    ex_mb.modify_region_font_format(sheet_kq, k, None, k, None, )
                    ex_mb.modify_region_alignment(sheet_kq, k, None, k, None, horizontal="center", vertical="center")
                    ex_mb.modify_region_border(sheet_kq, k, None, k, None)

                ex_mb.modify_cell_value(sheet_kq, 4, 6, "日期\n备注")

                rs = ex_mb.get_sheet_max_rows(sheet_kq) - 4
                ex_mb.modify_cell_value(sheet_kq, 3, 5, rs)

                # 设置打印区域
                ex_mb.set_print_area(sheet_kq, 5, None, ex_mb.get_sheet_max_rows(sheet_kq) + 0, None)

                # 另存为考勤表
                ex_mb.save_file(f"file/考勤表/{school}/{sheet}考勤表.xlsx")
                ex_mb.close_file()
            log_opt.write_success(f'【{school}】生成成功！')
        ex_main.close_file()
        return True
    except Exception as e:
        ex_main.close_file()
        return False


if __name__ == '__main__':
    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    ini_opt_school = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    log_opt.write_success('初始化成功！')

    # 获取gitee数据
    try:
        log_opt.write_info('正在获取gitee数据...')
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            # print(ini_opt.list_sections())
            file_name = ini_opt.get_section_option('main_xlsx', 'name')
            file_name_url = ini_opt.get_section_option('main_xlsx', 'url')
            # 获取钉钉数据
            plw_opt = playwright_package.Playwright_Management()
            log_opt.write_info('正在登陆钉钉...')
            if plw_opt.dingding_login():
                log_opt.write_success('登陆钉钉成功！')
                if plw_opt.dingding_file_download(file_name_url, f'file/{file_name}'):
                    plw_opt.close()
                    # 清洗数据
                    log_opt.write_info(f'正在对file/{file_name}进行数据清洗...')
                    if clean_data(f'file/{file_name}'):
                        log_opt.write_success(f'对file/{file_name}数据清洗成功！')
                    else:
                        raise Exception(f'对file/{file_name}数据清洗失败！')

                    # 生成考勤
                    log_opt.write_info(f'正在生成考勤表...')
                    if creat_kao_qin_sheet(f'file/{file_name}'):
                        log_opt.write_success('生成考勤表成功！')
                    else:
                        raise Exception('生成考勤表失败！')
                else:
                    raise Exception(f'下载【file/{file_name}】失败！')
            else:
                log_opt.write_error('登陆钉钉失败！')
                raise Exception('获取钉钉数据失败')
        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
